package com.jrx.anytxn.transaction.timer.job.marketingTask.step;

import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.customer.constant.CustomerConstant;
import com.jrx.anytxn.customer.entity.TlMarketingRecord;
import com.jrx.anytxn.feign.common.GateWayPredicate;
import com.jrx.anytxn.feign.gateway.response.EvidenceResponse02;
import com.jrx.anytxn.feign.gateway.service.IInnerGatewayService;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.service.IDealGatewayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 营销记录发送 - processor
 *
 * @author jing.xy
 */
@Service
public class MarketingCheckProcessor implements ItemProcessor<TlMarketingRecord, TlMarketingRecord> {

    Logger logger = LoggerFactory.getLogger(MarketingCheckProcessor.class);

    @Autowired
    private IDealGatewayService dealGatewayService;
    @Autowired
    private IInnerGatewayService innerGatewayService;

    @Override
    public TlMarketingRecord process(TlMarketingRecord record) throws Exception {
        // 调用接口，将营销信息推送至营销平台
        String evidenceRequest02Json = dealGatewayService.buildMarketCheckReq(record);
        GateWayPredicate<EvidenceResponse02> paymentPre = () -> innerGatewayService.checkMarketing(evidenceRequest02Json);

        String sumStatus = CustomerConstant.MARKET_SUM_STATUS_O;
        String returnMsg;

        EvidenceResponse02 evidenceResponse02 = null;
        try {
            evidenceResponse02 = paymentPre.getRes(paymentPre);
            returnMsg = evidenceResponse02.getBusMsg();
        } catch (Exception e) {
            logger.error("调用营销平台查证异常，流水号为：{}，异常原因：{}", record.getSeqNo(), e.getMessage());
            returnMsg = "调用营销平台查证异常";
        }
        if (null != evidenceResponse02){
            logger.debug("调用营销平台查证成功:结果为：[{}]，流水号为：{}",evidenceResponse02.toString(),record.getSeqNo());
            if("00001".equals(evidenceResponse02.getBusCode())){
                sumStatus = CustomerConstant.MARKET_SUM_STATUS_T;
            }
            if("00000".equals(evidenceResponse02.getBusCode())){
                sumStatus = CustomerConstant.MARKET_SUM_STATUS_S;
            }
            if("99999".equals(evidenceResponse02.getBusCode()) || StringUtils.isBlank(evidenceResponse02.getBusCode())){
                sumStatus = CustomerConstant.MARKET_SUM_STATUS_O;
            }
        }
        record.setSumStatus(sumStatus);
        record.setReturnMsg(returnMsg);
        record.setUpdateBy(TransBizConstant.SYS_OPRATE);
        return record;
    }

}
